﻿using AgencyManagerSystem.AsmType;
using AgencyManagerSystem.Common;
using AgencyManagerSystem.Core;
using AgencyManagerSystem.DataFetcher;
using AgencyManagerSystem.Model;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;

namespace AgencyManagerSystem.Controllers
{
    public class ProductionController : MyControllerBase
    {
        ProductionManager manager;
        ProductionFetcher fetcher;
        public ProductionController() : base()
        {
            this.manager = new ProductionManager();
            this.fetcher = new ProductionFetcher();
        }
        [HttpPost]
        [RoleFlagAuthorizeAttribute(PolicyDomain.Center, AppOpt.Create)]
        public AsmObject<ProductionModel> Set(ProductionModel productionModel)
        {
            if (productionModel == null)
            {
                DBHelper.Commit( false);
                LogHelper.Err(this.GetType(), String.Format("SET:从{0}中接收到空的参数", RequestIp));
                Response.StatusCode = (int)HttpStatusCode.BadRequest;
                return new AsmObject<ProductionModel>() { Message = "传入的参数不能为空", Result = AmsCode.ArgNotAccept };
            }
            LogHelper.Debug(this.GetType(), String.Format("SET:[RQS|{1}]{0}", Util.ConvertToJson(productionModel), RequestIp));
            var result = manager.Set(productionModel);
            LogHelper.Debug(this.GetType(), String.Format("SET:[RSP|{1}]{0}", Util.ConvertToJson(result), RequestIp));
            DBHelper.Commit( true);
            return result;
        }
        [HttpPost]
        [RoleFlagAuthorizeAttribute(PolicyDomain.Center, AppOpt.Delete)]
        public AsmObject<bool> Del(ProductionModel production)
        {
            if (production == null)
            {
                DBHelper.Commit( false);
                LogHelper.Err(this.GetType(), String.Format("SET:从{0}中接收到空的参数", RequestIp));
                Response.StatusCode = (int)HttpStatusCode.BadRequest;
                return new AsmObject<bool>() { Data = false, Message = "传入的参数不能为空", Result = AmsCode.ArgNotAccept };
            }
            LogHelper.Debug(this.GetType(), String.Format("DEL:[RQS|{1}]{0}", Util.ConvertToJson(production), RequestIp));
            var result = manager.Delete(production);
            LogHelper.Debug(this.GetType(), String.Format("DEL:[RSP|{1}]{0}", Util.ConvertToJson(result), RequestIp));
            DBHelper.Commit( true);
            return result;
        }
        [HttpPost]
        [RoleFlagAuthorizeAttribute(PolicyDomain.Center, AppOpt.Delete)]
        public AsmArray<Int32> BulkDel(dynamic jsonProductionModel)
        {
            LogHelper.Debug(this.GetType(), String.Format("BULKDEL:[RQS|{1}]{0}", jsonProductionModel, RequestIp));
            var models = Util.ConvertArrayFromJson<ProductionModel>((String)jsonProductionModel.data);
            if (models == null)
            {
                LogHelper.Err(this.GetType(), String.Format("BULKDEL:从{0}中接收到空的参数", RequestIp));
                Response.StatusCode = (Int32)HttpStatusCode.BadRequest;
                var errResponse = new AsmArray<Int32>() { Data = new List<Int32>(), Message = "传入的参数不能为空", Result = AmsCode.ArgNotAccept };
                LogHelper.Debug(this.GetType(), String.Format("BULKDEL:[RSP|{1}]{0}", Util.ConvertToJson(errResponse), RequestIp));
                return errResponse;
            }
            int faild = models.Count();
            var del = new List<Int32>();
            StringBuilder sb = new StringBuilder();
            foreach (var model in models)
            {
                var eff = manager.Delete(model);
                if (eff.Result != 0)
                {
                    sb.AppendFormat("{0}:{1}\r\n", model.AutoId, eff.Message);
                }
                else
                {
                    del.Add(model.AutoId);
                    faild--;
                }
            }
            DBHelper.Commit(true);
            var succResponse = new AsmArray<Int32>() { Data = del, Message = "共有" + (models.Count() - faild) + "笔资料删除成功", Result = AmsCode.Succ };
            LogHelper.Debug(this.GetType(), String.Format("BULKDEL:[RSP|{1}]{0}", Util.ConvertToJson(succResponse), RequestIp));
            return succResponse;
        }
        [HttpGet]
        [Authorize]
        //[RoleFlagAuthorizeAttribute(Definer.POLICY_DOMAIN_SUPER, AppOpt.Exec)]
        public AsmArray<ProductionModel> List(string jsonCondition, int pos, int size)
        {
            LogHelper.Debug(this.GetType(), String.Format("LIST:[RQS|{1}]{0}", jsonCondition, RequestIp));
            int cnt = 0;
            var productionModels = fetcher.List(Util.ConvertArrayFromJson<Condition>(jsonCondition), pos, size, out cnt);
            DBHelper.Commit( true);
            var result = new AsmArray<ProductionModel>() { Data = productionModels, Message = "操作成功", Result = AmsCode.Succ, Cnt = cnt };
            LogHelper.Debug(this.GetType(), String.Format("LIST:[RSP|{1}]{0}", Util.ConvertToJson(result), RequestIp));
            return result;
        }
        [HttpGet]
        [Authorize]
        //[RoleFlagAuthorizeAttribute(Definer.POLICY_DOMAIN_SUPER, AppOpt.Exec)]
        public AsmArray<ProductionModel> ListByKeyword(string keyword)
        {
            LogHelper.Debug(this.GetType(), String.Format("LISTBYKEYWORD:[RQS|{1}]{0}", keyword, RequestIp));
            var productionModels = fetcher.ListByKeyword(keyword);
            DBHelper.Commit(true);
            var result = new AsmArray<ProductionModel>() { Data = productionModels, Message = "操作成功", Result = AmsCode.Succ, Cnt = productionModels.Count };
            LogHelper.Debug(this.GetType(), String.Format("LISTBYKEYWORD:[RSP|{1}]{0}", Util.ConvertToJson(result), RequestIp));
            return result;
        }

        [HttpGet]
        [Authorize]
        //[RoleFlagAuthorizeAttribute(Definer.POLICY_DOMAIN_SUPER, AppOpt.Exec)]
        public AsmObject<ProductionModel> Get(int id)
        {
            LogHelper.Debug(this.GetType(), String.Format("GET:[RQS|{1}]{0}",id, RequestIp));
            var production = fetcher.Get(id);
            DBHelper.Commit( true);
            AsmObject<ProductionModel> result = null;
            if (production != null)
                result = new AsmObject<ProductionModel>() { Data = production, Message = "操作成功", Result = AmsCode.Succ };
            else
                result = new AsmObject<ProductionModel>() { Data = production, Message = "无法找到数据", Result = AmsCode.DataNotFound };
            LogHelper.Debug(this.GetType(), String.Format("GET:[RSP|{1}]{0}", Util.ConvertToJson(result), RequestIp));
            return result;
        }

        [HttpGet]
        [Authorize]
        //[RoleFlagAuthorizeAttribute(Definer.POLICY_DOMAIN_SUPER, AppOpt.Exec)]
        //PID=产品ID，dArr是对应维度的清单
        public AsmObject<decimal> GetPriceByProduction(int pid,string dArr )
        {
            LogHelper.Debug(this.GetType(), String.Format("GETPRICEBYPRODUCTION:[RQS|{1}]{0}", pid, RequestIp));
            var production = fetcher.Get(pid);
            var price = production.Price;
            var basePrice = price;
            string[] sArr = dArr.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            if(sArr.Length!=10)
            {
                DBHelper.Commit(true);
                return new AsmObject<decimal>() { Data = 0, Message = "操作失败,传入的参数有误", Result = AmsCode.ArgNotAccept };
            }
            DimensionFetcher dimensionFetcher = new DimensionFetcher();
            DimensionDocFetcher dimensionDocFetcher = new DimensionDocFetcher();

            IList<DimensionModel> dimensionModels = dimensionFetcher.List();
            foreach(DimensionModel dm in dimensionModels)
            {
                int lv = dm.Level;
                bool dmAvaliable = (Boolean)typeof(ProductionModel).GetProperty("Dimension" + lv).GetValue(production);
                if (dmAvaliable&&dm.PricingStrategy != 0)
                {
                    decimal pricePlus = 0;
                    try
                    {
                        if (lv <= 5)
                        {
                           var dmDoc = dimensionDocFetcher.Get(int.Parse(sArr[lv - 1]));
                            pricePlus =  dmDoc.Price;
                        }
                        else
                        {
                            var dmVar = dimensionDocFetcher.ListDetail(lv);
                            foreach(var detail in dmVar)
                            {
                                var d = decimal.Parse(sArr[lv - 1]);
                                if (detail.Max <= d && detail.Min >= d)
                                {
                                    pricePlus = detail.Price*d;
                                    break;
                                }
                            }
                        }
                        switch(dm.PricingStrategy)
                        {
                            case 1://基准乘
                                price += basePrice * pricePlus;//未来可能会有逻辑，先乘基准乘，再乘直接乘
                                break;
                            case 2://直接乘
                                price *= (1+pricePlus);
                                break;
                            case 3://加点
                                price += pricePlus;
                                break;
                        }
                    }
                    catch
                    {
                        //pricePlus = 0;
                    }
                }
            }

            DBHelper.Commit(true);
            AsmObject<decimal> result = null;
            if (price >0)
                result = new AsmObject<decimal>() { Data = price, Message = "操作成功", Result = AmsCode.Succ };
            else
                result = new AsmObject<decimal>() { Data = price, Message = "无法找到数据", Result = AmsCode.DataNotFound };
            LogHelper.Debug(this.GetType(), String.Format("GETPRICEBYPRODUCTION:[RSP|{1}]{0}", Util.ConvertToJson(result), RequestIp));
            return result;
        }
    }
}